package dao;

import entity.Type;
import util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

// 单点插入，单点删除，查询全部，返回 ArrayList
public class TypeDao {
   
    public boolean insert(Type type) {
        boolean res = false;
        String sql = "insert `type`(`name`) values(?)";

        try {
            Connection conn = DBUtil.getConn();

            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, type.getName());

            res = ps.executeUpdate() != 0 ? true : false;
            DBUtil.close(ps, conn);
        } catch(SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("数据访问失败");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("error！");
        } finally {
            return res;
        }
    }

    public boolean delete(Type type) {
        boolean res = false;
        String sql = "delete from `type` where `name` = ?";

        try {
            Connection conn = DBUtil.getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, type.getName());

            res = ps.executeUpdate() != 0 ? true : false;
            DBUtil.close(ps, conn);
        } catch(SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("数据访问失败");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("error！");
        } finally {
            return res;
        }
    }

    public ArrayList<Type> fetch() {
        ArrayList<Type> res = new ArrayList<Type>();
        String sql = "select * from `type`";

        try {
            Connection conn = DBUtil.getConn();
            PreparedStatement ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            
            while(rs.next()) {
                long id = Long.valueOf(rs.getString("id"));
                String name = rs.getString("name");

                res.add(new Type(id, name));
            }

            DBUtil.close(rs, ps, conn);
        } catch(SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("数据访问失败");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("error！");
        } finally {
            return res;
        }
    } 
}
